﻿using System;
using System.Linq;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Repositories.Impl;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class ExpireCertReportBuilder : ReportBuilderBase
    {
        private readonly CertRegisterRepository _certRepository;

        public override string TemplateFileName
        {
            get { return "Сертификаты, срок действия которых истекает"; }
        }

        public ExpireCertReportBuilder(CertRegisterRepository repository)
        {
            _certRepository = repository;
        }

        public override string Create(CreateReportModel model)
        {
            var report = new ExpiringCertificatesReportType
                {
                    CreateDate = DateTime.Today
                };
            var query = _certRepository.GetAll().ValidCertificates();
            if (model.Value.HasValue)
            {
                report.AmountDays = model.Value.Value.ToString();
                query = query.ExpiredCertificates( model.Value.Value );
            }
            else
            {
                report.AmountDays = String.Empty;
            }
            var certificates = query.OrderBy(s => s.UserRegister.LastName)
                .Select(s => new {s.UserRegister.FirstName, s.UserRegister.MotherName, s.UserRegister.LastName, s.IdentityCenter.IdentityCenterName,
                    s.SerialNumber, s.FromDate, s.ToDate, InfoSystems = s.CertRegisterInfoSystems.Select(g => g.InfoSystem.InfoSystemName)})
                .AsEnumerable()
                .Select( s => new ExpiringCertificatesReportTypeCertificates
                    {
                        CertificationAuthority = s.IdentityCenterName,
                        FirstName = s.FirstName,
                        MiddleName = s.MotherName,
                        SecondName = s.LastName,
                        LimitationDate = String.Format("{0:dd.MM.yyyy} - {1:dd.MM.yyyy}", s.FromDate, s.ToDate),
                        SerialNumber = s.SerialNumber,
                        Systems = String.Join( "\r\n", s.InfoSystems )
                    } ).ToArray();
            report.Certificates = certificates.ToArray();
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}